﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class LevelController : BaseController
    {
        /// <summary>
        /// Declare Level Repository
        /// </summary>
        private LevelRepository levelRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionLevelSort = "SessionLevelSort";
        public static string SessionLevelSearch = "SessionLevelSearch";
        public static string SessionLevelSortOpt = "SessionLevelSortOpt";



        // GET: /Level/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public LevelController()
            : base()
        {
            this.levelRepository = new LevelRepository();
            ViewBag.SelectedMenuId = 25;
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Trình Độ";
            // Stored Session
          
            Session[SessionLevelSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionLevelSort];
            Session[SessionLevelSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionLevelSortOpt];

            var level = this.levelRepository.ListLevels(false).ToList();

            // Search
            if (Session[SessionLevelSearch] != null)
            {
                ViewBag.Keyword = Session[SessionLevelSearch].ToString();

                level = level.Where(l => l.Name.ToUpper().Contains(ViewBag.Keyword.ToUpper())).ToList();

            }
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionLevelSort] != null)
            {
                switch (Session[SessionLevelSort].ToString())
                {
                    case "name":
                        level = Session[SessionLevelSortOpt].ToString().Equals("desc") ? level.OrderByDescending(s => s.Name).ToList() : level.OrderBy(s => s.Name).ToList();

                        Session[SessionLevelSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionLevelSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(level.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(LevelModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.levelRepository.HasNameExisted(model.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên trình độ đã được sử dụng");
                }


                var level = new Level();
                level.Id = (int)model.Id;
                level.Name = model.Name;
                level.Description = model.Description;

                this.levelRepository.CreateLevel(level);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công trình độ mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;

            var level = this.levelRepository.GetLevelById(id);
            var levelModel = new LevelModel(level);

            // population dropdow list


            return View(levelModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(LevelModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.levelRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên trình độ đã được sử dụng");
                }

                var level = new Level();

                level.Id = (int)model.Id;
                level.Name = model.Name;
                level.Description = model.Description;

                this.levelRepository.UpdateLevel(level);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công trình độ này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.levelRepository.DeleteLevel(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công trình độ này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.levelRepository.DeleteLevel(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những trình độ này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionLevelSearch] = null;
            Session[SessionLevelSort] = null;
            Session[SessionLevelSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.levelRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.levelRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên trình độ đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
